package co.yixiang.mall.biz.quartz.controller;
/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co

 */
import co.yixiang.common.core.annotation.AnonymousAccess;
import co.yixiang.common.core.exception.BadRequestException;
import co.yixiang.common.log.annotation.Log;
import co.yixiang.common.mproot.dozer.service.IGenerator;
import co.yixiang.mall.biz.quartz.service.QuartzJobRebateService;
import co.yixiang.mall.biz.quartz.service.QuartzLogRebateService;
import co.yixiang.mall.biz.quartz.utils.QuartzRebateManage;
import co.yixiang.mall.common.quartz.domain.QuartzJobRebate;
import co.yixiang.mall.common.quartz.dto.QuartzJobRebateDto;
import co.yixiang.mall.common.quartz.dto.QuartzJobRebateQueryCriteria;
import co.yixiang.mall.common.quartz.dto.QuartzLogRebateDto;
import co.yixiang.mall.common.quartz.dto.QuartzLogRebateQueryCriteria;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author hupeng
 * @date 2019-01-07
 */
@Slf4j
@RestController
@Api(tags = "系统:定时任务管理")
@RequestMapping("/jobs")
public class QuartzJobRebateController {

    private static final String ENTITY_NAME = "quartzJob";

    private final QuartzJobRebateService quartzJobService;
    private final IGenerator generator;
    private final QuartzLogRebateService quartzLogService;
    @Autowired
    QuartzRebateManage rebateManage;

    @AnonymousAccess
    @GetMapping(value = "/test")
    public String test(){
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime executeTime = localDateTime.plusSeconds(10);
        QuartzJobRebate jobRebate = new QuartzJobRebate();
        jobRebate.setExecuteTime(Timestamp.valueOf(executeTime));
        jobRebate.setJobName("测试返佣");
        jobRebate.setBeanName("rebateTask");
        jobRebate.setCronExpression("0/5 * * * * ? ");
        jobRebate.setMethodName("run");
        jobRebate.setIsPause(false);
        jobRebate.setParams("{order:1}");
        System.out.println(executeTime+"   "+Timestamp.valueOf(executeTime));
        rebateManage.addJob(jobRebate);
        return "111";
    }


    public QuartzJobRebateController(QuartzJobRebateService quartzJobService, IGenerator generator, QuartzLogRebateService quartzLogService) {
        this.quartzJobService = quartzJobService;
        this.generator = generator;
        this.quartzLogService = quartzLogService;
    }

    // @Log("查询定时任务")
    @ApiOperation("查询定时任务")
    @GetMapping
    @PreAuthorize("hasAnyAuthority('admin','timing:list')")
    public ResponseEntity<Object> getJobs(QuartzJobRebateQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(quartzJobService.queryAll(criteria,pageable), HttpStatus.OK);
    }

    @Log("导出任务数据")
    @ApiOperation("导出任务数据")
    @GetMapping(value = "/download")
    @PreAuthorize("hasAnyAuthority('admin','timing:list')")
    public void download(HttpServletResponse response, QuartzJobRebateQueryCriteria criteria) throws IOException {
        quartzJobService.download(generator.convert(quartzJobService.queryAll(criteria), QuartzJobRebateDto.class), response);
    }

    @Log("导出日志数据")
    @ApiOperation("导出日志数据")
    @GetMapping(value = "/logs/download")
    @PreAuthorize("hasAnyAuthority('admin','timing:list')")
    public void downloadLog(HttpServletResponse response, QuartzLogRebateQueryCriteria criteria) throws IOException {
        quartzLogService.download(generator.convert(quartzLogService.queryAll(criteria), QuartzLogRebateDto.class), response);
    }

    @ApiOperation("查询任务执行日志")
    @GetMapping(value = "/logs")
    @PreAuthorize("hasAnyAuthority('admin','timing:list')")
    public ResponseEntity<Object> getJobLogs(QuartzLogRebateQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(quartzLogService.queryAll(criteria,pageable), HttpStatus.OK);
    }


    @Log("新增定时任务")
    @ApiOperation("新增定时任务")
    @PostMapping
    @PreAuthorize("hasAnyAuthority('admin','timing:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody QuartzJobRebate resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        return new ResponseEntity<>(quartzJobService.save(resources), HttpStatus.CREATED);
    }


    @Log("修改定时任务")
    @ApiOperation("修改定时任务")
    @PutMapping
    @PreAuthorize("hasAnyAuthority('admin','timing:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody QuartzJobRebate resources){
        quartzJobService.updateById(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }


    @Log("更改定时任务状态")
    @ApiOperation("更改定时任务状态")
    @PutMapping(value = "/{id}")
    @PreAuthorize("hasAnyAuthority('admin','timing:edit')")
    public ResponseEntity<Object> updateIsPause(@PathVariable Long id){
        quartzJobService.updateIsPause(quartzJobService.getOne(new LambdaQueryWrapper<QuartzJobRebate>()
                .eq(QuartzJobRebate::getId,id)));
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }


    @Log("执行定时任务")
    @ApiOperation("执行定时任务")
    @PutMapping(value = "/exec/{id}")
    @PreAuthorize("hasAnyAuthority('admin','timing:edit')")
    public ResponseEntity<Object> execution(@PathVariable Long id){
        quartzJobService.execution(quartzJobService.getOne(new LambdaQueryWrapper<QuartzJobRebate>().eq(QuartzJobRebate::getId,id)));
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }


    @Log("删除定时任务")
    @ApiOperation("删除定时任务")
    @DeleteMapping
    @PreAuthorize("hasAnyAuthority('admin','timing:del')")
    public ResponseEntity<Object> delete(@RequestBody Integer[] ids){
        quartzJobService.removeByIds(new ArrayList<>(Arrays.asList(ids)));
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

